var appPath = getAppPath();	

$(function(){
	$("#queryUserId").combobox({
		url:appPath+'/itbCoupon/getOrgUserForCombo.action?blkFlg=1&orgId=1',
		valueField:'id',
		textField:'name',
		onSelect:function(selRecdU){
			// TODO
		}
	});
	
	initJspGrid();
	initSaleGrid();
});

// 模版列表初始化
function initJspGrid(){
	
	$('#tmplGrid').datagrid({
	    url:appPath + "/itbTmpl/getTmplList.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
			{field:'editTmpl',title:'编辑',width:35,align:'center',sortable:false,
				formatter:function(value,rowData,rowIndex){
					if(!rowData.tmpl_id) return "";
					var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑模版' ";
					ret += " onClick='editTmpl("+rowData.tmpl_id+","+rowData.base_tmpl_id+","+rowData.publish+")'/></a>";
					return ret;
				}
			},
	        {field:'tmpl_id',title:'模版ID',width:40,align:'left',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return '<span style="color:red">'+value+'</span>';
		    	  }
		      },
	        {field:'base_tmpl_id',title:'样版ID',width:40,align:'left',sortable:false},
	        {field:'tmpl_name',title:'模版名称',width:110,align:'left',sortable:false},
	        {field:'user_id',title:'作者',width:95,align:'left',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return '<span style="color:red">'+value+'</span>['
		    		  	+(rowData.user_name||rowData.nickname||'<span style="color:red">未命名</span>')+']';
		    	  }
		      },
	        {field:'order',title:'显示顺序',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.tmpl_id) return "";
		    		  return "<a href='javascript:void(0)' onClick='editOrder("+rowData.tmpl_id+","+rowData.order+")'>"+rowData.order+"</a>";
		    	  }
		      },
	        {field:'vip',title:'VIP',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.tmpl_id) return "";
		    		  var show = '普通模版';
		    		  if(Number(value||'0')==10) show="<span style='color:red;'>VIP模版</span>";
		    		  return "<a href='javascript:void(0)' onClick='editVip("+rowData.tmpl_id+","+rowData.vip+")'>"+show+"</a>";
		    	  }
		      },
	        {field:'editType',title:'模版分类',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.tmpl_id) return "";
		    		  return "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/tip.png' title='编辑分类' onClick='editType("+rowData.tmpl_id+")'/></a>";
		    	  }
		      },
		    {field:'keyword',title:'关键词',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.tmpl_id) return "";
		    		  var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='设置' ";
					  ret += " onClick='editKeyword("+rowData.tmpl_id+")'/></a>";
					  return ret;
		    	  }
		      },
		    {field:'topic',title:'专题',width:40,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.tmpl_id) return "";
		    		  var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='设置' ";
					  ret += " onClick='editTopic("+rowData.tmpl_id+",3)'/></a>";
					  return ret;
		    	  }
		      },
	        {field:'publish',title:'制作状态',width:45,align:'center',sortable:false,
	        	formatter:function(publish, rowData, rowIndex){
	        		if (publish == 1 || publish =="1") return "<span style='color:red;'>已完成</span>";
	        		return '制作中';
	        	}}, 
	        {field:'sale',title:'售价设定',width:60,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.tmpl_id) return "<span style='color:red;'>N/A</span>";
		    		  var show = '<span style="color:green">免费</span>';
		    		  if(Number(rowData.tmpl_price_cnt||'0')>0) {
		    			  show = rowData.tmpl_price_cnt+'条价目';
		    		  }
		    		  return "<a href='javascript:void(0)' onClick='showSaleList("+rowData.tmpl_id+")'>"+show+"</a>";
		    	  }
		      },
		    {field:'shApply',title:'用户作品',width:60,align:'center',sortable:false,
		        	formatter:function(publish, rowData, rowIndex){
		        		var dcnt = Number(rowData.dcnt||'0');
		        		return '<a href="javascript:void(0)" onclick="shApply('+rowData.tmpl_id+')">查看【'+dcnt+'】</a>';
		        	}
		    },
	        {field:'create_time',title:'创建时间',width:60,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:60,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'添加模版',
			iconCls:'icon-add',
			handler:function(){
				addTmpl();
			}
		},
		{
			text:'发布模版',
			iconCls:'icon-ok',
			handler:function(){
				doPublish();
			}
		},
		{
			text:'取消发布',
			iconCls:'icon-cancel',
			handler:function(){
				cancelPublish();
			}
		},
		{
			text:'删除模版',
			iconCls:'icon-cancel',
			handler:function(){
				delTmpl();
			}
		}]
	    
	});
}

/**
 * View the list of user PPT
 * @param id
 */
function shApply(id){
	$("#udocForm").form('clear');
	$("#uDocTable").show();
	$("#temp_id").html("模板ID:"+id);
	$("#uDocDlg").window({
		title :'显示用户PPT文档信息',
		iconCls :'icon-blank',
		modal :true,
		shadow :true,
		collapsible :false,
		minimizable :false,
		maximizable :false
	});
	$('#uDocDlg').window('move',{top:20,left:20});
	$('#uDocDlg').window('open');
	initUserdocGrid(id);
}

/**Initializes the load user document information
 */
function initUserdocGrid(id){
	$('#uDocGrid').datagrid({
	    url:appPath + "/itbTmpl/getPptTempUserdoc.action?tempId="+id,
	    height:'full',
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam3(),
	    singleSelect:true,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    columns:[[
			{field : 'thumb',title : '缩略图',width : 25,align : 'center',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					var retUrl = '';
					if (value) {
						retUrl = '<a href="' +value+ '" target="_blank">'
							+ '<div style="display:table;text-align:center;height:60px;width:70px;">'
							+ '<span align="center" style="display:table-cell;vertical-align:middle">'
							+ '<img src="'+value+'?x-oss-process=image/resize,m_lfit,h_100,w_100'
							+ '" style="display:inline;max-height:60px;max-width:60px;"/></span></div></a>';
					}
					return retUrl;
				}
			},
			{field:'doc_id',title:'用户作品ID',width:25,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var show = value;
	        		if (Number(value||'0')>0) {
	        			var url = getHomeServer()+'/preview/pDoc?docId='+value;
	        			show = '<a href="' + url + '" target="_blank">'+value+'</a>';
	        		}
	        		return show;
	        	}
	        },
	        {field:'doc_name',title:'文档名称',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(value){
  	        			return '<span style="color:	#555555;">'+value+'</span>';
  	        		}
	        		return '<span style="color:#B0B0B0;">暂无</span>';
	        	}
		    },
	        {field:'purpose',title:'文档分类',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var tem = '';
  	        		switch(Number(value||'0')){
	  	        		case 0: tem ='<span style="color:green;">普通文档</span>'; break;
	  	        		case 1: tem ='<span style="color:#FFBBFF;">测试用</span>'; break;
	  	        		case 2: tem ='<span style="color:blue;">印品订单</span>'; break;
  	        		}
  	        		return tem;
	        	}
		    },
		    {field :'user_id',title :'用户ID', width:25, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if(value){
		    			return '<span style="color:#555555;">'+value+'</span>';
		    		}
		    	}
		    },
		    {field :'user_type',title :'用户分类', width:25, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		var tem = '';
		    		switch(Number(value||'0')){
		    		case 0: tem = '<span style="color:#FFA07A">后台</span>';
		    		case 1: tem = '<span style="color:#FFA07A">用户</span>';
		    		}
		    		return tem;
		    	}
		    },
		    {field :'nickname',title :'用户昵称', width:40, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if(value){
		    			return '<span style="color:#436EEE;">'+value+'</span>';
		    		}
		    		return '<span style="color:#BEBEBE;">昵称暂无</span>';
		    	}
		    },
		    {field :'mobile',title :'手机号', width:30, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return value || '<span style="color:#FF83FA">暂未填写</span>';
		    	}
		    },
	        {field:'create_time',title:'创建时间',width:45,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	});
}



//售价条目
function initSaleGrid(){
	$('#saleGrid').datagrid({
	    url:appPath + "/itbTmpl/getTmplPriceInfoLst.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam2(),
	    singleSelect:true,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'price_id',title:'价目ID',width:35,align:'left',sortable:false},
	        {field:'price',title:'售价',width:50,align:'right',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.price_id || !rowData.tmpl_id) return '<span style="color:red;">N/A</span>';
	        		return (Number(value||'0')/100)+'元';
	        	}
		    },
	        {field:'period',title:'有效时长',width:50,align:'right',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		return Number(value||'0')+'天';
	        	}
		    },
	        {field:'free',title:'限时免费',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.price_id || !rowData.tmpl_id) return '<span style="color:red;">N/A</span>';
	        		var show = (Number(value||'0')==1)?'<span style="color:red;">YES</span>':'NO';
	        		return "<a href='javascript:void(0)' onClick='editFree("+rowData.price_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	});
}

/**
 * 添加模版
 */
function addTmpl(){

//	$("#addFrame").attr("src", appPath + "/js/egret/index.html");
//	$('#addDlg').window({
//		title:'新建模版',
//		iconCls:'icon-add',
//		modal: true,
//		shadow: true,
//		collapsible:false,
//		minimizable:false,
//		maximizable:false
//	});
//	
//	$('#addDlg').window('move',{top:20,left:20});
//	$('#addDlg').window('open');
	
	var egretUrl = appPath+"/js/egret_t/index.html";
	window.open(egretUrl);
}

/**
 * 编辑模版
 */
function editTmpl(docId, mstTmplId, publish){
	/*var selectTmpl=$("#tmplGrid").datagrid("getChecked");
	if(!selectTmpl || selectTmpl.length != 1){
		$.messager.alert('提示信息','请选择一个模版进行编辑！','warning');
		return;
	}
	
	var docId = "";
	$.each(selectTmpl, function(index, item){
		docId = item.doc_id;
		return false;
	});*/
	
	//$("#editFrame").attr("src", appPath + "/itbTmplWeb/editTmplInit.action?id="+ tmplId);
//	$("#editFrame").attr("src", appPath + "/js/egret/index.html?docId="+docId);
//	$('#editDlg').window({
//		title:'编辑模版',
//		iconCls:'icon-edit',
//		modal: true,
//		shadow: true,
//		collapsible:false,
//		minimizable:false,
//		maximizable:false
//	});
//	
//	$('#editDlg').window('move',{top:20,left:20});
//	$('#editDlg').window('open');
	
	if (publish == 1 || publish =="1") {
		$.messager.alert('提示信息','请勿编辑已发布模版！','warning');
	} else {
		var egretUrl = appPath+"/js/egret_t/index.html?docId="+docId+"&mstId="+mstTmplId;
		window.open(egretUrl);
	}
}

/**
 * 显示顺序
 */
function editOrder(docId, order){
	$("#docId").val(docId);
	$("#order").val(order);
	
	$("#orderBtn").show();
	$('#orderDlg').window({
		title:'模版显示顺序设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#orderDlg').window('move',{top:20,left:20});
	$('#orderDlg').window('open');
}
/**
 * 修改模版显示顺序
 */
function doUpdOrder(){
	var docId = $("#docId").val();
	var order = $("#order").val();
	if(!order || order.length == 0 || Number(order)>999 || Number(order)<=0){
		$.messager.alert('提示信息','有效数值范围为：1～999','warning');
		return;
	}
	
	var url = appPath+"/itbTmplWeb/updTmplOrder.action?docId="+docId+"&order="+order;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','显示顺序已更新！','info',function(){
				doQuery();
				$('#orderDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','显示顺序更新失败！','warning');
		}
	});
}

/**
 * 结束模版显示顺序编辑
 */
function cancelUpdOrder(){
	$('#orderDlg').window('close');
}

/**
 * 模版分类
 */
function editType(docId){
	
	$("#docId").val(docId);
	$("#typeBtn").show();
	$('#typeDlg').window({
		title:'模版分类设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#typeDlg').window('move',{top:20,left:20});
	$('#typeDlg').window('open');
	
	initChk(docId);
}

function initChk(docId){
	$("input[name='tmplTypeInfo']").prop("checked", false);
	
	var url = appPath+"/itbTmpl/getTmplType.action?docId="+docId;
	$.post(url,function(data){
		if (data != null && data.length>0) {
			for (i in data) {
				var id = data[i];
				$("#typeId"+ id).prop('checked', true);
			}
		}
	});
}

/**
 * 修改模版分类信息
 */
function doPostData(){
	var typeIds = $("input[name='tmplTypeInfo']:checked").map(function(){
        	return $(this).val();
        }).get().join(',');
	
	var docId = $("#docId").val();
	var url = appPath+"/itbTmplWeb/updTmplType.action?docId="+docId+"&typeIds="+typeIds;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','模版分类已更新！','info');
		}
	});
}

/**
 * 结束模版分类编辑
 */
function cancelPostData(){
	$('#typeDlg').window('close');
}

/**
 * 发布模版
 */
function doPublish(){
	var selectTmpl=$("#tmplGrid").datagrid("getChecked");
	if(!selectTmpl || selectTmpl.length == 0){
		$.messager.alert('提示信息','请选择未发布模版进行处理！','warning');
		return;
	}else if(selectTmpl.length>1){
		$.messager.alert('提示信息','请选择单个模版进行处理！','warning');
		return;
	}
	
	var ids = "";
	var doFlg = false;
	$.each(selectTmpl, function(index, item){
		if(item.publish != 1 && item.publish != '1'){
			doFlg = true;
			//ids = ids + item.tmpl_id + ",";
			ids=item.tmpl_id;
		}
	});
	
	if(!doFlg){
		$.messager.alert('提示信息','请选择未发布模版进行处理！','warning');
		return;
	}
	
	$.messager.confirm("确认",
		"是否确认发布模版？<br/><span style='color:red'>#请确保模版已经过认真检查 </span>",
		function (r) {
	        if (r) {
	        	$.loading(true);
	        	
// Deleted 2017-12-12
	        	// 更新切换模版用数据
//				var postUrl = getPublishServer()+'/publish/publishTmpl';
//			    var sendData = {
//			    	tmplId:ids,
//			    	userId:g_userId,
//			    	updFlg:1
//			    };
//			    $.post(postUrl, sendData, function(ret){
//			        if (ret.success == 1) {
//			        	console.log('switch/refreshRelInfo OK');
			        	
			        	// 发布模版
			        	var url = appPath+"/itbTmplWeb/doPublish.action?ids="+ids;
			        	$.post(url,function(ret){
			        		$.loading(false);
			        		if(ret=="ok"){
			        			$.messager.alert('提示信息','模版发布成功！','info');
			        			doQuery();
			        		} else if (ret=="ng"){
			        			$.messager.alert('提示信息','所选文档存在未生成预览图的文档页，请先生成预览！','warning');
			        		} else {
			        			$.messager.alert('提示信息','模版发布失败！','warning');
			        		}
			        	});
	        			
// Deleted 2017-12-12
	        			// 添加搜索信息到redis
//	        			var url3 = getApiServer()+'/v5/api4back/addDesignToRedis?ppt=1&id='+ids;
//	        			$.post(url3,function(addRet){
//				        	$.loading(false);
//	        				
//	        				var msg='模版已发布!';
//	        				if(addRet.success != 1) {
//	        					msg+='</br>*添加redis搜索信息失败';
//	        				}
//	        				
//	        				$.messager.alert('提示信息',msg,'info');
//		        			doQuery();
//	        			});
			        	
//			        } else {
//			        	$.loading(false);
//			        	console.log(ret.msg);
//			        	$.messager.alert('提示信息',ret.msg,'warning');
//			        }
//			    });
	        }
		}
	);
}

/**
 * 取消发布
 */
function cancelPublish(){
	var selectTmpl=$("#tmplGrid").datagrid("getChecked");
	if(!selectTmpl || selectTmpl.length == 0){
		$.messager.alert('提示信息','请选择已发布模版进行处理！','warning');
		return;
	}else if(selectTmpl.length>1){
		$.messager.alert('提示信息','请选择单个模版进行处理！','warning');
		return;
	}
	
	var ids = "";
	var doFlg = false;
	$.each(selectTmpl, function(index, item){
		if(item.publish == 1 || item.publish == '1'){
			doFlg = true;
			//ids = ids + item.tmpl_id + ",";
			ids=item.tmpl_id;
		}
	});
	
	if(!doFlg){
		$.messager.alert('提示信息','请选择已发布模版进行处理！','warning');
		return;
	}
	
	$.messager.confirm("确认", "是否确认取消已发布模版？", function (r) {
		if(r){
			$.loading(true);
// Deleted 2017-12-12
        	// 更新切换模版用数据
//			var postUrl = getPublishServer() + '/publish/cancelTmpl';
//		    var sendData = {
//		    	tmplId:ids,
//		    	userId:g_userId,
//		    	updFlg:1
//		    };
//		    $.post(postUrl, sendData, function(ret){
//		        if (ret.success == 1) {
//		        	console.log('switch/cancelTmpl OK');
		        	
		        	// 取消发布
		        	var url = appPath+"/itbTmplWeb/cancelPublish.action?ids="+ids;
					$.post(url,function(data){
						$.loading(false);
						if(data=="ok"){
							$.messager.alert('提示信息','模版已取消发布！','info');
							doQuery();
						} else {
							$.messager.alert('提示信息','模版取消发布失败!','warning');
						}
					});
					
// Deleted 2017-12-12
					// 清除搜索信息到redis
//        			var url3 = getApiServer()+'/v5/api4back/delDesignToRedis?ppt=1&id='+ids;
//        			$.post(url3,function(delRet){
//			        	$.loading(false);
//        				
//        				var msg='模版已取消发布!';
//        				if(delRet.success != 1) {
//        					msg+='</br>*删除redis搜索信息失败';
//        				}
//        				
//        				$.messager.alert('提示信息',msg,'info');
//	        			doQuery();
//        			});
//		        	
//		        } else {
//		        	$.loading(false);
//		        	console.log(ret.msg);
//		        	$.messager.alert('提示信息',ret.msg,'warning');
//		        }
//		    });
		}
	});
}

/**
 * 删除模版
 */
function delTmpl(){
	var selectItem=$("#tmplGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择模版','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认删除", function (r) {  
        if (r) { 
			var ids = "";
			$.each(selectItem, function(index, item){
				ids = ids + item.tmpl_id + ",";
			});
			var url = appPath+"/itbTmplWeb/deleteTmpl.action?ids="+ids;
			$.post(url,function(data){
				if(data=="ok"){
					$.messager.alert('提示信息','删除成功','info');
					doQuery();
				}
			});
        }
	});
}

/**
 * 模版价目表
 */
function showSaleList(tmplId){
	$("#sDId").val(tmplId).html(tmplId);
	doQuery2();
	
	$("#saleBtn").show();
	$('#saleListDlg').window({
		title:'模版价目表',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#saleListDlg').window('move',{top:20,left:20});
	$('#saleListDlg').window('open');
}
function closeSaleList(){
	$('#saleListDlg').window('close');
}

// 添加价格条目
function addSale(){
	$('#saleEditForm').form('clear');
	
	var dId = Number($("#sDId").val()||'0');
	$("#sEdtDId").val(dId).html(dId);
	
	$("#saleEditBtn").show();
	$('#saleEditDlg').window({
		title:'模版售价设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#saleEditDlg').window('move',{top:20,left:20});
	$('#saleEditDlg').window('open');
}
function doSaleEdit(){
	var dId = Number($("#sEdtDId").val() || '0');
	var price = Number($("#sEdtPrice").val() || '0');
	var period = Number($("#sEdtPeriod").val() || '0');
	if(isNaN(price) || price==0 || isNaN(period) || period==0) {
		$.messager.alert('提示信息','请填写正确的售价及有效时长！','warning');
		return;
	}
	
	var url = appPath+"/itbTmplWeb/addTmplPrice.action"
	var sendData = {
		"tmplPriceInfo.type": 3,// PPT
		"tmplPriceInfo.tmpl_id": dId,
		"tmplPriceInfo.price": price,
		"tmplPriceInfo.period": period
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','提交成功','info');
			$('#saleEditDlg').window('close');
			doQuery2();
        } else {
        	$.messager.alert('提示信息','提交失败','info');
        }
    });
}
function cancelSaleEdit(){
	$('#saleEditDlg').window('close');
}
// 删除价格条目
function delSale(){
	var selectItem=$("#saleGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择价格条目','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认删除", function (r) {  
        if (r) { 
			var ids = "";
			$.each(selectItem, function(index, item){
				ids = ids + item.price_id + ",";
			});
			var url = appPath+"/itbTmplWeb/delTmplPrice.action?ids="+ids;
			$.post(url,function(data){
				if(data=="ok"){
					$.messager.alert('提示信息','删除成功','info');
					doQuery2();
				}else{
					$.messager.alert('提示信息','删除失败','info');
				}
			});
        }
	});
}

// 设置限免
function editFree(){
	// TODO
}

//设定vip模版
function editVip(designId, vip){
	$("#vDId").val(designId);
	$("#updVip").combobox('select',Number(vip||'0')||0);
	
	$("#vipBtn").show();
	$('#vipDlg').window({
		title:'VIP模版设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#vipDlg').window('move',{top:20,left:20});
	$('#vipDlg').window('open');
}
function doUpdVip(){
	var docId = $("#vDId").val();
	var vip = $("#updVip").combobox('getValue');
	if((Number(docId||'0')||0) <= 0) {
		$.messager.alert('提示信息','无效模版ID!','warning');
		return;
	}
	
	var url = appPath+"/itbTmplWeb/updTmplVip.action?docId="+docId+"&vip="+vip;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','vip属性已更新！','info',function(){
				doQuery();
				$('#vipDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','vip属性更新失败！','warning');
		}
	});
}
function cancelUpdVip(){
	$('#vipDlg').window('close');
}

/**
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	
	var findType1 = $("#queryTmplType1").val();
	var findType2 = $("#queryTmplType2").val();
	var findPubFlg = $("#queryPublish").combobox('getValue');
	var findTmplName=$("#queryTmplName").val();
	var findTmplId=$("#queryTmplId").val();
	var findUserId = $("#queryUserId").combobox('getValue');
	
	if (findType1&&findType1.length>0) {
		queryObject.findTmplType = findType1;
		if (findType2&&findType2.length>0) {
			queryObject.findTmplType = findType1+","+findType2;
		} 
	} else if (findType2&&findType2.length>0) {
		queryObject.findTmplType = findType2;
	}
	if(findPubFlg&&findPubFlg.length>0) queryObject.findPubFlg = findPubFlg;
	if(findTmplName&&findTmplName.length>0) queryObject.findTmplName = findTmplName;
	if((Number(findTmplId||'0')||0) > 0) queryObject.findTmplId = findTmplId;
	if((Number(findUserId||'0')||0) > 0) queryObject.findUserId = findUserId;
	
	return queryObject;
}

function getQueryParam2(){
	var queryObject = {
		docId: Number($("#sDId").val()||'0')
	};
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(startFlg){
	$("#tmplGrid").datagrid('unselectAll');
	if(startFlg==1){
		$("#tmplGrid").datagrid('load', getQueryParam());
	} else {
		$("#tmplGrid").datagrid('reload', getQueryParam());
	}
}

function doQuery2(){
	$("#saleGrid").datagrid('unselectAll');
	$("#saleGrid").datagrid('load', getQueryParam2());
}

function editKeyword(dId){
	$("#kwDId").val(dId);
	$('#keywordTable').html('');
	
	var url = appPath+"/itbTmpl/getKeywordLst.action?docId="+dId;
	$.post(url,function(ret){	
		if(ret && ret.length>0){
			for(var i=0; i<ret.length; i++){
				var sub = ret[i];
				if(sub && sub.length>0 && sub[0].type!=10){
					var itemHtml = '<tr><td class="queryTitle" width="80px">'+sub[0].type_name+'标签</td>'+
							'<td class="queryContent" colspan="4">';
					for(var n=0; n<sub.length; n++){
						var chk = (Number(sub[n].doc_id||'0')>0)?"checked":"";
						itemHtml += '<div style="width:80px;float:left">'+
							'<input type="checkbox" '+chk+' id="kwId_'+sub[n].key_id+'" name="keywordInfo" value="'+sub[n].key_id+'"/>'+
							sub[n].key_name+'</div>';
					}
					itemHtml += '</td></tr>';
					$('#keywordTable').append(itemHtml);
				}
			}
			
			$('#keywordTable').append('<tr><td class="queryTitle" width="80px">自定义标签</td>'+
					'<td class="queryContent" width="60px"><input class="inputText" type="text" id="myKwName_1"/></td>'+
					'<td class="queryContent" width="60px"><input class="inputText" type="text" id="myKwName_2"/></td>'+
					'<td class="queryContent" width="60px"><input class="inputText" type="text" id="myKwName_3"/></td>'+
					'<td class="queryContent" width="60px"><input class="inputText" type="text" id="myKwName_4"/></td>'+
					'</tr>');

			for(var i=0; i<ret.length; i++){
				var sub = ret[i];
				if(sub && sub.length>0 && sub[0].type==10){
					var cnt=1;
					for(var n=0; n<sub.length; n++){
						if(cnt<=4){
							$('#myKwName_'+cnt).val(sub[n].key_name);
							cnt+=1;
						}
					}
					break;
				}
			}
		}
	});
	
	// show dlg
	$("#keywordBtn").show();
	$('#keywordDlg').window({
		title:'关键词标签设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#keywordDlg').window('move',{top:20,left:20});
	$('#keywordDlg').window('open');
}
function updKW(){
	var defKeys = $("input[name='keywordInfo']:checked").map(function(){
        	return $(this).val();
        }).get();
	
	var userKeys = [];
	for(var i=1; i<=4; i++){
		var keyNm = $('#myKwName_'+i).val();
		if(keyNm && keyNm.length>0) userKeys.push(keyNm);
	}
	
	var dId = $("#kwDId").val();
	
	var url = getDesignServer()+'/encrypt/encrypt';
	var data = encryptParas({
		'type':3,
		'uId':g_userId,
		'dId':dId,
		'defKeys': defKeys,
		'userKeys': userKeys,
		'destination': '/user/updDocKw'
		});
	$.post(url,data,function(ret){
		if(ret.success == 1){
			$.messager.alert('提示信息','关键词标签已更新！','info');
		}else{
			$.messager.alert('提示信息',(ret.msg||'更新失败'),'info');
		}
	});
}
function cancelKW(){
	$('#keywordDlg').window('close');
}

//专题窗口
function editTopic(dId,topType){
	$("#stDId").val(dId);
	$("#stType").val(topType);//3
	$('#topicTable').html('');
	
	var url = appPath+"/itbDesign/getTopicInfoLst.action?typeIds=3&designId="+dId;
	$.post(url,function(ret){	
		if(ret && ret.length>0){
			for(var i=0; i<ret.length; i++){// 按use分组
				var sub = ret[i];
				if(sub && sub.length>0 && sub[0].type==topType){
					var useNm = '专题';
					if(sub[0].use==1){
						useNm = '热门';
					}
					var itemHtml = '<tr><td class="queryTitle" width="80px">'+useNm+'</td>'+
							'<td class="queryContent" colspan="4">';
					for(var n=0; n<sub.length; n++){
						var chk = (Number(sub[n].item_id||'0')>0)?"checked":"";
						itemHtml += '<div style="width:80px;float:left">'+
							'<input type="checkbox" '+chk+' id="stId_'+sub[n].key_id+'" name="topicInfo" value="'+sub[n].st_id+'"/>'+
							sub[n].title+'</div>';
					}
					itemHtml += '</td></tr>';
					$('#topicTable').append(itemHtml);
				}
			}
		}
	});
	
	// show dlg
	$("#topicBtn").show();
	$('#topicDlg').window({
		title:'热门/主题设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#topicDlg').window('move',{top:20,left:20});
	$('#topicDlg').window('open');
}
function updTopic(){
	var stIds = $("input[name='topicInfo']:checked").map(function(){
        	return $(this).val();
        }).get();//.join(',')
	
	var dId = $("#stDId").val();
	var topType = $("#stType").val();//3
	
	var url = getDesignServer()+'/encrypt/encrypt';
	var data = encryptParas({
		'type':topType,
		'dId':dId,
		'stIds': stIds,
		'destination': '/user/updDocTopic'
		});
	$.post(url,data,function(ret){
		if(ret.success == 1){
			$.messager.alert('提示信息','热门/专题已更新！','info');
		}else{
			$.messager.alert('提示信息',(ret.msg||'更新失败'),'info');
		}
	});
}
function cancelTopic(){
	$('#topicDlg').window('close');
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

//用户文档
function doQuery3(){
	$("#uDocGrid").datagrid('unselectAll');
	$("#uDocGrid").datagrid('load', getQueryParam3());
}

//
function getQueryParam3(){
	var obj = {};
	var docId = $("#queryDocId").val();
	var userId = $("#queryUId").val();
	var mobile = $("#queryMobile").val();
	if(Number(docId)>0) obj.findDocId = docId;
	if(Number(userId)>0) obj.findUId = userId;
	if(Number(mobile)>=0){
		obj.findMobile = mobile;
	}else{
		$.messager.alert('提示信息','请输入有效数字!','info');
	} 
	return obj;
}
